//
//  TakeListViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/26.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "TakeListViewController.h"
#import "SocketRequest.h"
#import "TakeExpress.h"
#import "TakeExpressCell.h"
#import "MultipleTakeExpressCell.h"
#import "Singleton.h"
#import "CustomAlertView.h"

@interface TakeListViewController ()<SocketRequestDelegate,CustomAlertViewDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_selectedExpressList;
    NSString *_errorMessage;//取件错误信息展示
    NSMutableArray *_failReceiveList;
    BOOL _isTakedSuccess;
    NSMutableArray *_successReceiveList;
}

@end

@implementation TakeListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _isTakedSuccess = NO;
        _successReceiveList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = [NSString stringWithFormat:@"可取快递（%lu）",(unsigned long)self.takeExpressList.count];
    if (self.isSingle) {
        self.tableView.scrollEnabled = NO;
        _bottomView.hidden = YES;
        _singleBottomView.frame = CGRectMake(0, 0, 320, 80);
        self.tableView.tableFooterView = _singleBottomView;
        _selectedExpressList = [NSMutableArray arrayWithArray:self.takeExpressList];
    } else {
        _selectedExpressList = [NSMutableArray arrayWithArray:self.takeExpressList];
        [self reloadSelecteAllBtn];
    }
}

- (void)takeSuccessBackLastVC {
    if ([_delegate respondsToSelector:@selector(successTakeExpresses:)]) {
        [_delegate successTakeExpresses:_successReceiveList];
    }
    [self backLastViewController];
}

- (void)sureTakeExpressSocket {
    [ToastActivity makeActivity:@"快递签收中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS6"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    NSMutableString *mutableString = [NSMutableString stringWithString:@""];
    for (TakeExpress *takeExpress in _selectedExpressList) {
        if ([takeExpress.expressType isEqualToString:@"0006"] || [takeExpress.expressType isEqualToString:@"0002"]) {//待自提
            [mutableString appendString:@"1,"];
        } else if ([takeExpress.expressType isEqualToString:@"0031"] || [takeExpress.expressType isEqualToString:@"0005"]) {//待配送
            [mutableString appendString:@"2,"];
        }
        [mutableString appendString:takeExpress.inwayExpressId];
        [mutableString appendString:[NSString stringWithFormat:@",%d",self.sendType]];
        [mutableString appendString:@"|"];
    }
    NSData *stringData = [mutableString dataUsingEncoding:NSUTF8StringEncoding];
    [mutableData appendData:[SocketMethod hexDataWithLength:stringData.length]];
    [mutableData appendData:stringData];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//签收结束处理
- (void)finishReceive {
    //对数组处理
    NSMutableArray *selectedArray = [NSMutableArray arrayWithArray:_selectedExpressList];
    [selectedArray removeObjectsInArray:_failReceiveList];
    [_successReceiveList addObjectsFromArray:selectedArray];
    NSMutableArray *allArray = [NSMutableArray arrayWithArray:self.takeExpressList];
    [allArray removeObjectsInArray:selectedArray];
    self.takeExpressList = allArray;
    //签收结果展示
    if (_failReceiveList.count <= 0) {
        NSString *text = [NSString stringWithFormat:@"已成功领取%d个快递",(int)_selectedExpressList.count];
        [DSToast showText:text InView:self.view];
        [self performSelector:@selector(takeSuccessBackLastVC) withObject:nil afterDelay:1];
    } else {
        [self reloadSelecteAllBtn];
        [self.tableView reloadData];
        CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"签收失败快件" message:_errorMessage delegate:self cancelButtonTitle:@"确定" sureButtonTitle:nil];
        [alert show];
    }
    [_selectedExpressList removeObjectsInArray:selectedArray];
}

//处理错误信息
- (void)handleErrorMessage:(NSString *)errorMessage {
    NSArray *sonArray = [errorMessage componentsSeparatedByString:@","];
    NSString *inwayExpressId = [SocketMethod subArray:sonArray Index:0];
    NSString *error = [SocketMethod subArray:sonArray Index:1];
    for (TakeExpress *takeExpress in _selectedExpressList) {
        if ([inwayExpressId isEqualToString:takeExpress.inwayExpressId]) {
            [_failReceiveList addObject:takeExpress];
            if (_errorMessage) {
                _errorMessage = [NSString stringWithFormat:@"%@ %@\n%@",takeExpress.expressId,error,_errorMessage];
            } else {
                _errorMessage = [NSString stringWithFormat:@"%@ %@",takeExpress.expressId,error];
            }
        }
    }
}

#pragma mark CustomAlertViewDelegate
- (void)customAlertView:(CustomAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self takeSuccessBackLastVC];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        NSString *content = [SocketMethod stringDecryHexData:data];
        DLog(@"%@",content);
        NSArray *array = [content componentsSeparatedByString:@"|"];
        for (NSString *string in array) {
            if (string.length > 0) {
                [self handleErrorMessage:string];
            }
        }
        _isTakedSuccess = YES;
        [self finishReceive];
    } else {
        [DSToast showText:msg InView:self.view];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [ToastActivity dismissInView:self.view];
    [DSToast showText:msg InView:self.view];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.takeExpressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 143;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isSingle) {
        static NSString *CellIndentifier = @"TakeExpressCell";
        TakeExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"TakeExpressCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        TakeExpress *takeExpress = [self.takeExpressList objectAtIndex:indexPath.row];
        [cell reloadTakeExpressCellWithTakeExpress:takeExpress];
        return cell;
    } else {
        static NSString *CellIndentifier = @"MultipleTakeExpressCell";
        MultipleTakeExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MultipleTakeExpressCell" owner:self options:nil] lastObject];
        }
        TakeExpress *takeExpress = [self.takeExpressList objectAtIndex:indexPath.row];
        if ([_selectedExpressList containsObject:takeExpress]) {
            [cell reloadMultipleTakeExpressCellWithTakeExpress:takeExpress Selected:YES];
        } else {
            [cell reloadMultipleTakeExpressCellWithTakeExpress:takeExpress Selected:NO];
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:NSClassFromString(@"MultipleTakeExpressCell")]) {
        TakeExpress *takeExpress = [self.takeExpressList objectAtIndex:indexPath.row];
        if ([_selectedExpressList containsObject:takeExpress]) {
            [_selectedExpressList removeObject:takeExpress];
        } else {
            [_selectedExpressList addObject:takeExpress];
        }
        [self reloadSelecteAllBtn];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.isSingle) {
        return 0;
    }
    return 48;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    footerView.backgroundColor = [UIColor clearColor];
    return footerView;
}

- (void)reloadSelecteAllBtn {
    if (_selectedExpressList.count == self.takeExpressList.count) {
        _selectedAllBtn.selected = YES;
    } else {
        _selectedAllBtn.selected = NO;
    }
    NSString *title = [NSString stringWithFormat:@"领取快递（%lu）",(unsigned long)_selectedExpressList.count];
    [_muchBtn setTitle:title forState:UIControlStateNormal];
}

#pragma mark NibAction
- (IBAction)selectedAllExpressAction:(id)sender {
    [_selectedExpressList removeAllObjects];
    if (_selectedAllBtn.selected) {
        _selectedAllBtn.selected = NO;
    } else {
        _selectedAllBtn.selected = YES;
        _selectedExpressList = [NSMutableArray arrayWithArray:self.takeExpressList];
    }
    [self reloadSelecteAllBtn];
    [self.tableView reloadData];
}

- (IBAction)takeExpressAction:(id)sender {
    if (_selectedExpressList.count <= 0) {
        [DSToast showText:@"请选择快递" InView:self.view];
    } else {
        _errorMessage = nil;
        _failReceiveList = [NSMutableArray arrayWithCapacity:1];
        [self sureTakeExpressSocket];
    }
}

- (void)dealloc {
    _socketRequest = nil;
    _takeExpressList = nil;
    _selectedExpressList = nil;
    _failReceiveList = nil;
}

@end
